import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050505);

const camera = new THREE.PerspectiveCamera(65, innerWidth / innerHeight, 1, 10000);
camera.position.z = 1400;

const circleGmt = new THREE.CircleBufferGeometry(1, 6);
const gmt = new THREE.InstancedBufferGeometry();
gmt.index = circleGmt.index;
gmt.attributes = circleGmt.attributes;

const particleCount = 5000;
const translateArray = [];
for(let i = 0; i < particleCount; i += 1) {
  translateArray.push(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1)
}
gmt.setAttribute('translate', new THREE.InstancedBufferAttribute(new Float32Array(translateArray), 3));
gmt.maxInstancedCount = particleCount;

const mtl = new THREE.ShaderMaterial({
  uniforms: {
    map: { value: new THREE.TextureLoader().load('../../textures/sprite/circle.png') },
    time: { value: 0.0 }
  },
  vertexShader: document.getElementById('vertexShader').textContent,
  fragmentShader: document.getElementById('fragmentShader').textContent,
  depthTest: true,
  depthWrite:true
});

const mesh = new THREE.Mesh(gmt, mtl);
mesh.scale.set(500, 500, 500);
scene.add(mesh);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const stats = new Stats();
document.body.appendChild(stats.dom);

const render = () => {
  const time = performance.now() * .0005;

  mtl.uniforms['time'].value = time;

  mesh.rotation.x = time * .2;
  mesh.rotation.y = time * .4;

  renderer.render(scene, camera);
}

const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  render();
}
animate();

const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);
